package com.itheima.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

public class Ticket12306 implements Runnable {

    private CuratorFramework client;
    //分布式锁
    private InterProcessMutex lock;
    //模拟数据库中的总票数
    private int tickets = 100;

    //创建锁
    public Ticket12306() {
        //重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);

        //第二种方式（推荐）：
        client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .namespace("huawei")
                .build();
        //开启连接
        client.start();

        lock = new InterProcessMutex(client, "/mylock");
    }


    @Override
    public void run() {
        while (true) {

            try {
                //获取锁
                lock.acquire(8, TimeUnit.SECONDS);

                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "正在买票，还剩:" + (tickets-1)+"张票");
                    Thread.sleep(100);
                    tickets--;
                }else {
                    break;
                }
            } catch (Exception e) {

            } finally {
                try {
                    //释放锁
                    lock.release();
                } catch (Exception e) {

                }
            }


        }
    }
}
